package com.kenyi.co.ui.home.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.kenyi.co.R;
import com.kenyi.co.common.ui.BaseActivity;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.home.adapter.SearchAdapter;
import com.kenyi.co.ui.home.bean.SearchBean;
import com.kenyi.co.ui.home.db.RecordsDao;
import com.kenyi.co.ui.video.VideoDetailActivity;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.kenyi.co.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

import static com.kenyi.co.utils.CommonUtils.isFastClick;


/**
 * 搜索页面
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "SearchActivity";


    private List<SearchBean.DatasBean> itemList;
    private LRecyclerView mRecyclerView = null;
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    private SearchAdapter mDataAdapter = null;
    private TextView tv_search_cannel;

    private EditText et_fenlei_search;
    private View mEmptyView;
    private ImageView iv_search_cannel, iv_main_search;
    private RelativeLayout re_search_header;

    private RecordsDao mRecordsDao;
    //默然展示词条个数
    private final int DEFAULT_RECORD_NUMBER = 10;
    private List<String> recordList = new ArrayList<>();
    private List<String> record = new ArrayList<>();
    private TagAdapter mRecordsAdapter;
    private LinearLayout mHistoryContent;
    private TagFlowLayout tagFlowLayout;
    private ImageView clearAllRecords;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_search);
        initView();
        //默认账号
        String username = "007";
        //初始化数据库
        mRecordsDao = new RecordsDao(this, username);
        tagFlowLayout = findViewById(R.id.fl_search_records);
        clearAllRecords = findViewById(R.id.clear_all_records);


        mHistoryContent = findViewById(R.id.ll_history_content);
        inithisdata();

        mRecyclerView = (LRecyclerView) findViewById(R.id.list);
        mDataAdapter = new SearchAdapter(SearchActivity.this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.default_divider_height_10)
                .setPadding(R.dimen.default_divider_padding_10)
                .setColorResource(R.color.white)
                .build();
        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能
        mRecyclerView.setLoadMoreEnabled(false);
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mRecyclerView.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
            @Override
            public void reload() {

            }
        });
        mRecyclerView.refresh();


        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                SearchBean.DatasBean item = mDataAdapter.getDataList().get(position);
                if (!isFastClick()) {
                    return;
                }
                Intent metags = new Intent(SearchActivity.this, VideoDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("id", item.getId() + "");
//                bundle.putString("id", "1907030516");
                metags.putExtras(bundle);
                startActivity(metags);

            }
        });

//        getSearchList("");

        et_fenlei_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String skey = et_fenlei_search.getText().toString().trim();
                    getSearchList(skey);
                    String hiskey = SharepUtils.getString_info(SearchActivity.this, SharepUtils.SEARCH_HISTORY);
                    if (!hiskey.contains(skey + "ad")) {
                        if (StringUtils.isNotEmptypro(hiskey)) {
                            SharepUtils.setString_info(SearchActivity.this, skey + "ad" + hiskey, SharepUtils.SEARCH_HISTORY);
                        } else {
                            SharepUtils.setString_info(SearchActivity.this, skey + "ad", SharepUtils.SEARCH_HISTORY);
                        }
                    }


                }
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_fenlei_search.getWindowToken(), 0);
                return false;
            }
        });
        et_fenlei_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    iv_search_cannel.setVisibility(View.GONE);
                    return;
                } else {
                    iv_search_cannel.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    protected void inithisdata() {
        initOldData();

        //创建历史标签适配器
        //为标签设置对应的内容
        mRecordsAdapter = new TagAdapter<String>(recordList) {

            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(SearchActivity.this).inflate(R.layout.tv_history,
                        tagFlowLayout, false);
                //为标签设置对应的内容
                tv.setText(s);

                return tv;
            }
        };


        tagFlowLayout.setAdapter(mRecordsAdapter);
        tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public void onTagClick(View view, int position, FlowLayout parent) {
                //清空editText之前的数据
                et_fenlei_search.setText("");
                //将获取到的字符串传到搜索结果界面,点击后搜索对应条目内容
                et_fenlei_search.setText(recordList.get(position));

                et_fenlei_search.setSelection(et_fenlei_search.getText().toString().length());
                getSearchList(et_fenlei_search.getText().toString());

            }
        });


        //view加载完成时回调
        tagFlowLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                boolean isOverFlow = tagFlowLayout.isOverFlow();
                boolean isLimit = tagFlowLayout.isLimit();
//                if (isLimit && isOverFlow) {
//                    moreArrow.setVisibility(View.VISIBLE);
//                } else {
//                    moreArrow.setVisibility(View.GONE);
//                }
            }
        });

//        moreArrow.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                tagFlowLayout.setLimit(false);
//                mRecordsAdapter.notifyDataChanged();
//            }
//        });

        //清除所有记录
        clearAllRecords.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //清除所有数据
                mRecordsDao.deleteUsernameAllRecords();

            }
        });


        mRecordsDao.setNotifyDataChanged(new RecordsDao.NotifyDataChanged() {
            @Override
            public void notifyDataChanged() {
                initOldData();
            }
        });
    }

    protected void initOldData() {

        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                emitter.onNext(mRecordsDao.getRecordsByNumber(DEFAULT_RECORD_NUMBER));
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(List<String> s) throws Exception {
                        recordList.clear();
                        record.clear();
                        recordList = s;
                        for (int i=10;i<recordList.size();i++) {
                            recordList.remove(i);
                        }
                        if (null == recordList || recordList.size() == 0) {
                            mHistoryContent.setVisibility(View.GONE);
                        } else {
//                                mHistoryContent.setVisibility(View.VISIBLE);
                        }
                        if (mRecordsAdapter != null) {
                            mRecordsAdapter.setData(recordList);
                            mRecordsAdapter.notifyDataChanged();
                        }
                    }
                });

    }

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.white));//设置状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        }
    }

    private void initView() {
        setStatusBar();
        mEmptyView = findViewById(R.id.empty_view);

        tv_search_cannel = findViewById(R.id.tv_search_cannel);
        et_fenlei_search = findViewById(R.id.et_fenlei_search);
        iv_search_cannel = findViewById(R.id.iv_search_cannel);

        tv_search_cannel.setOnClickListener(this);
        iv_search_cannel.setOnClickListener(this);
        iv_search_cannel.setVisibility(View.GONE);

        initData();

    }

    private void initData() {
        et_fenlei_search.requestFocus();
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(et_fenlei_search, 0);
        String keys = SharepUtils.getString_info(SearchActivity.this, SharepUtils.SEARCH_HISTORY);

    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {


            case R.id.iv_search_cannel:
                et_fenlei_search.setText("");
                initData();
                mEmptyView.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.GONE);

                mHistoryContent.setVisibility(View.VISIBLE);
                break;


            case R.id.tv_search_cannel:
                finish();
                break;
        }
    }

    /**
     * 获取系统头像库
     */
    public void getSearchList(final String key) {

        Map<String, String> params = new HashMap<>();

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_fenlei_search.getWindowToken(), 0);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        String url = NetConfig.SEARCH_LIST + "?key=" + key;

        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                        mRecyclerView.refreshComplete(10);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        int num = 0;

                        SearchBean packlist = gson.fromJson(response, SearchBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            mRecordsDao.addRecords(key);


                            mHistoryContent.setVisibility(View.GONE);
                            if (itemList != null) {
                                mDataAdapter.clear();
                                itemList.clear();
                            }
                            itemList = new ArrayList<SearchBean.DatasBean>();
                            itemList = packlist.getDatas();
                            num = itemList.size();
                            if (num == 0) {
                                mEmptyView.setVisibility(View.VISIBLE);
                                mRecyclerView.setVisibility(View.GONE);

                                mHistoryContent.setVisibility(View.GONE);

                            } else {
                                mEmptyView.setVisibility(View.GONE);
                                mRecyclerView.setVisibility(View.VISIBLE);

                            }

                            mDataAdapter.addAll(itemList);
                            mRecyclerView.refreshComplete(num);

                        }


                    }
                });
    }


}
